/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { routerRedux } from 'dva/router';
import { getYzList } from '@/services/report';
import {
  kbGetArearList,
  getBrandsList,
  getHtAuth,
  bigScreenLogin,
  getScreenLoginInfo,
} from '@/services/api';
import { isLegalData, saveCookie, removeCookie, getLStorage } from '@/utils/utils';
import { message } from 'antd';

export default {
  namespace: 'global',

  state: {
    authority: null,
    tabActiveKeys: {},
    collapsed: false,
    yzList: [],
    siteList: [],
    kbCompaniesTreeList: [],
    brandList: [],
    hasAuthToChangeHtPwd: false,
    screenLoginInfo: {}, // 新零售大屏登录的用户信息
    screenToken: null, // 新零售大屏登录后的token
  },

  effects: {
    *navigator({ payload }, { put }) {
      const { search, pathname } = payload;
      yield put(
        routerRedux.push({
          pathname,
          search,
        }),
      );
    },
    *getYzList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getYzList, payload);
      if (!response) return;
      const { code, data } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            yzList: isLegalData(data, []),
          },
        });
        __dva_resolve(isLegalData(data, []));
      } else {
        __dva_reject(response);
      }
    },
    // 获取站点列表
    *getSiteList({ payload }, { call, put }) {
      const response = yield call(getYzList, payload);
      if (!response) return;
      const { code, data } = response;
      if (code == 0 && data) {
        yield put({
          type: 'save',
          payload: {
            siteList: data,
          },
        });
      } else {
        yield put({
          type: 'save',
          payload: {
            yzList: [],
          },
        });
      }
    },
    // 获取快宝驿站所属区域
    *kbGetArearList({ payload, __dva_resolve, __dva_reject }, { call, put, select }) {
      const { user_info } = yield select(({ user }) => user.currentUser);

      const { phone, inn_area_ids = [], area_ids } = user_info;
      const cacheAreaId = getLStorage(`KB_INN_AREA_${phone}`);
      const isCompany = area_ids == '*';
      // 防止片区被关闭，导致请求带上上一个的片区ID
      const area_id = inn_area_ids.includes(cacheAreaId)
        ? cacheAreaId
        : isCompany
          ? '0'
          : inn_area_ids.join(',');

      const response = yield call(kbGetArearList, { ...payload, area_id });
      if (!response) return;
      const { code, data, msg } = response;
      const treeList = [];
      treeList.push(...isLegalData(data, []));
      // level为4代表支局，支局没有下一级
      for (let i = 0; i < treeList.length; i++) {
        const val = treeList[i];
        val.level == '4' ? (val.isLeaf = true) : (val.isLeaf = false);
      }

      if (code == 0 && data) {
        yield put({
          type: 'save',
          payload: {
            kbCompaniesTreeList: treeList,
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 获取快递品牌
    *getBrandList({ payload, __dva_resolve, __dva_reject }, { call, put, select }) {
      const { brandList } = yield select(_ => _.global);
      if (brandList && brandList.length > 0) {
        __dva_resolve(brandList);
        return;
      }
      const response = yield call(getBrandsList, payload);
      if (!response) return;
      const { code, data } = response;
      if (code == 0 && data) {
        yield put({
          type: 'save',
          payload: {
            brandList: isLegalData(data, []),
          },
        });
        __dva_resolve(isLegalData(data, []));
      } else {
        __dva_reject();
      }
    },
    // 判断当前账号是否拥有修改百世巴枪密码的权限
    *judgeCurrentUserChangeHTPwdAuth({ payload }, { call, put, select }) {
      const { currentUser = {} } = yield select(_ => _.user);
      const { roles = [], sub_privilege = [] } = currentUser;
      const hasMenuAuthority = roles.includes('system') || sub_privilege.includes('system');

      if (!hasMenuAuthority) return;

      const response = yield call(getHtAuth, payload);
      if (!response) return;

      const { code } = response || {};
      const hasAuth = code == 0;
      yield put({
        type: 'save',
        payload: {
          hasAuthToChangeHtPwd: hasAuth,
        },
      });
    },
    // 新零售大屏，登录
    *bigScreenLogin({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(bigScreenLogin, payload);
      if (!response) return;

      const { code, msg, data = {} } = response || {};
      if (code == 0) {
        message.success(msg);
        const { token } = data;
        saveCookie(`${payload.sign}`, token, 180 * 24 * 60 * 60);
        yield put({
          type: 'save',
          payload: {
            screenToken: token,
          },
        });
        __dva_resolve(data);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 新零售大屏，获取登录用信息
    *getScreenLoginInfo({ payload, __dva_resolve, __dva_reject }, { call, put, select }) {
      const { screenKey } = yield select(_ => _.global) || {};
      const response = yield call(getScreenLoginInfo, payload);

      if (!response) return;
      const { code, data = {}, msg } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            screenLoginInfo: isLegalData(data, {}),
          },
        });
        __dva_resolve(isLegalData(data, {}));
      } else {
        message.error(msg);
        removeCookie(screenKey);
        __dva_reject(code);
      }
    },
  },
  reducers: {
    changeLayoutCollapsed(state, { payload }) {
      return {
        ...state,
        collapsed: payload,
      };
    },
    changeTabActiveKey(state, { payload }) {
      return {
        ...state,
        tabActiveKeys: {
          ...state.tabActiveKeys,
          ...payload,
        },
      };
    },
    changeAuthority(state, { payload }) {
      return {
        ...state,
        authority: {
          ...state.authority,
          ...payload,
        },
      };
    },
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },

  subscriptions: {
    setup({ history }) {
      return history.listen(({ pathname, search, hash }) => {
        if (window.aplus_queue && pathname) {
          window.aplus_queue.push({
            action: 'aplus.sendPV',
            arguments: [{ is_auto: false }],
          });
        }
      });
    },
  },
};
